package com.grj.parkingsystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.grj.parkingsystem.common.JwtUtil;
import com.grj.parkingsystem.entity.ParkingReservation;
import com.grj.parkingsystem.entity.ParkingSpace;
import com.grj.parkingsystem.entity.User;
import com.grj.parkingsystem.mapper.UserMapper;
import com.grj.parkingsystem.service.ParkingReservationService;
import com.grj.parkingsystem.mapper.ParkingReservationMapper;
import com.grj.parkingsystem.service.ParkingSpaceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
* @author ganru
* @description 针对表【t_parking_reservation(车位预订表)】的数据库操作Service实现
* @createDate 2025-05-16 16:51:44
*/
@Service
@Slf4j
public class ParkingReservationServiceImpl extends ServiceImpl<ParkingReservationMapper, ParkingReservation>
    implements ParkingReservationService{

    @Resource
    private ParkingSpaceService parkingSpaceService;

    @Resource
    private UserMapper userMapper;

    @Resource
    private JwtUtil jwtUtil;

    @Override
    @Transactional
    public boolean createReservation(String token, Long parkingLotId, Long spaceId,
                                     String startTimeStr, String endTimeStr) {

        // 解析Token
        String username = jwtUtil.getUsernameFromToken(token);
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", username));

        // 检查车位是否可预订
        ParkingSpace space = parkingSpaceService.getById(spaceId);
        if (space == null || space.getStatus() != 0) {
            log.error("车位 {} 不存在或状态不正确", spaceId);
            return false;
        }

        // 解析时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date startTime, endTime;
        try {
            startTime = sdf.parse(startTimeStr);
            endTime = sdf.parse(endTimeStr);
        } catch (Exception e) {
            log.error("时间格式错误");
            return false;
        }

        // 检查时间合法性
        Date now = new Date();
        if (startTime.before(now) || endTime.before(startTime)) {
            log.error("时间不合法");
            return false;
        }

        // 创建预订记录
        ParkingReservation reservation = new ParkingReservation();
        reservation.setUserId(user.getId());
        reservation.setParkingLotId(parkingLotId);
        reservation.setSpaceId(spaceId);
        reservation.setReservationTime(now);
        reservation.setStartTime(startTime);
        reservation.setEndTime(endTime);
        reservation.setStatus(0); // 0: 待使用

        boolean success = save(reservation);

        if (success) {
            // 占用车位
            parkingSpaceService.reserveSpace(spaceId);
        }

        return success;
    }

    @Override
    public List<ParkingReservation> getUserReservations(String token) {

        // 解析Token
        String username = jwtUtil.getUsernameFromToken(token);
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", username));

        return baseMapper.selectList(new QueryWrapper<ParkingReservation>()
                .eq("user_id", user.getId())
                .orderByDesc("create_time"));
    }

    @Override
    @Transactional
    public boolean cancelReservation(String token, Long reservationId) {
        // 解析Token
        String username = jwtUtil.getUsernameFromToken(token);
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", username));

        ParkingReservation reservation = baseMapper.selectById(reservationId);

        if (!reservation.getUserId().equals(user.getId())) {
            return false;
        }

        if (reservation.getStatus() != 0) {
            return false;
        }

        reservation.setStatus(2); // 2: 已取消
        boolean success = updateById(reservation);

        if (success) {
            // 释放车位
            parkingSpaceService.releaseSpace(reservation.getSpaceId());
        }

        return success;
    }
}




